package com.mtw.bbs.bbsUser.utils;


import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.fileAdmin.feign.FileClient;
import com.mtw.bbs.fileAdmin.pojo.vo.FileVo;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import com.mtw.bbs.userAdmin.pojo.vo.BaseUserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 头像工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AvatarUtilz {


    private final FileClient fileClient;

    /**
     * 设置用户头像url
     */
    public void setAvatarUrls(List<? extends BaseUserVo> list){

        String[] fileIds = list.stream().map(BaseUserVo::getAvatar).filter(StringUtils::isNotBlank).toArray(String[]::new);
        Result<List<FileVo>> fileUrls = fileClient.getFileUrlByIdArray(fileIds);
        Map<String, String> urlMap;
        if (fileUrls.isSuccess()){
            urlMap = fileUrls.getData().stream().collect(HashMap::new, (map, item) -> map.put(item.getId(), item.getUrl()), HashMap::putAll);
        }else {
            urlMap = new HashMap<>(1);
        }
        list.forEach(x->{
            if (urlMap.get(x.getAvatar()) != null){
                x.setAvatar(urlMap.get(x.getAvatar()));
            }
        });
    }

    /**
     * 设置用户头像url
     */
    public void setAvatarUrl(BaseUserVo obj){

        if (StringUtils.isNotBlank(obj.getAvatar())){
            Result<FileVo> fileUrl = fileClient.getUrl(obj.getAvatar());
            if (fileUrl.isSuccess() && fileUrl.getData().getUrl() != null){
                obj.setAvatar(fileUrl.getData().getUrl());
            }
        }
    }

}
